package com.lzh.dfs;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.lzh.common.pojo.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author lizuhu
 * @date 2021/6/28 13:48
 */
@RestController
@RequestMapping("/dfs")
public class FileController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 上传文件
     * @param file 前端传来的文件对象
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), StringUtils.getFilenameExtension(file.getOriginalFilename()), null);
        String fullPath = storePath.getFullPath();
        String server = fdfsWebServer.getWebServerUrl();
        String realUrl = server + fullPath;
        HashMap<String, String> map = new HashMap<>();
        map.put("url",realUrl);
        return Result.ok(map);
    }

    /**
     * 下载图片
     * @param images
     * @return
     */
    @PostMapping("/downLoad")
    public List<byte[]> downLoadFile(@RequestBody List<String> images){
        List<byte[]> bytesList = new ArrayList<>();
        for (String image : images) {
            //解析路径
            StorePath storePath = StorePath.parseFromUrl(image);
            //返回字节数组
            byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadCallback<byte[]>() {
                @Override
                public byte[] recv(InputStream ins) throws IOException {
                    byte[] bytes1 = IOUtils.toByteArray(ins);
                    return bytes1;
                }
            });
            bytesList.add(bytes);
        }
        return bytesList;
    }
}
